
package com.hcloud.auth.audit.handler;

import com.hcloud.auth.api.user.HcloudUserDetails;
import com.hcloud.auth.audit.service.LoginLogService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * 登录成功后的事件，记录日志
 *认证事件
 *
 * AuthenticationFailureConcurrentLoginEvent验证失败，同时登陆。
 *
 * AuthenticationFailureCredentialsExpiredEvent验证失败，凭证失效。
 *
 * AuthenticationFailureDisabledEvent验证失败，禁用。
 *
 * AuthenticationFailureExpiredEvent验证失败，失效。
 *
 * AuthenticationFailureLockedEvent验证失败，锁定。
 *
 * AuthenticationFailureProviderNotFoundEvent验证失败，找不到provider。
 *
 * AuthenticationFailureProxyUntrustedEvent验证失败，不可信任的代理。
 *
 * AuthenticationFailureServiceExceptionEvent验证失败，服务异常
 *
 * AuthenticationSuccessEvent认证成功。
 *
 * AuthenticationSwitchUserEvent切换用户。
 *
 * InteractiveAuthenticationSuccessEvent内部验证成功。
 *
 * 验证事件
 *
 * AuthenticationCredentialsNotFoundEvent找不到凭证。
 *
 * AuthorizationFailureEvent认证失败。
 *
 * AuthorizedEvent认证成功
 *
 * PublicInvocationEvent公用调用。
 * @author hepangui
 * @date 2018/11/29
 */
@Slf4j
@AllArgsConstructor
@Component
public class LoginSuccessHandler implements ApplicationListener<AuthenticationSuccessEvent> {

    private final LoginLogService loginLogService;

    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        System.out.println(event.getClass());
        Authentication authentication = (Authentication) event.getSource();
        var userDetail = (HcloudUserDetails) authentication.getPrincipal();
        loginLogService.saveSuccessLog(userDetail.getBaseUser().getAccount(), userDetail.getBaseUser().getName());
        log.info("{}:用户登录成功", userDetail.getUsername());
    }

}
